<?php

namespace App\Jobs;

use App\Constant\QueueKey;
use App\Events\RepayMentEvent;
use App\Models\RepayRecord;
use App\Models\RepayRecordMoney;
use App\Models\RepayRecordMonth;
use App\Models\RepaySummary;
use App\Models\SettingChannel;
use App\Models\UserGlobal;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class RepayMonthJobQueue implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $tries = 3;
    protected $id;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($recordId)
    {
        $this->onQueue(QueueKey::QUEUE_REPAY_MONTH);
        $this->id = $recordId;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //月保费 && 资方 => 月保费 => 公共
        $recordInfo = RepayRecord::with(['money','month','common'])->where('id',$this->id)->first();
        if(!$recordInfo){
            Log::debug('还款:请求月保费接口:没有数据' . $this->id);
            return;
        }

        //todo 判断是否是农信的
        $is_channel = RepaySummary::getLoanChannel($recordInfo->summary_id);
        if(false == $is_channel){
            Log::debug('还款:请求月报接口:是农信的' . $this->id);
            return;
        }

        //判断资方接口是否成功,只有成功才能处理这个接口
        $money_status = $recordInfo->money->status;
        if($money_status != RepayRecordMoney::STATUS_FOUR){
            //改变为轮询中,让轮询处理
            UserGlobal::where('uid',$recordInfo->uid)->update(['global_status' => UserGlobal::STATUS_REPAY_ING]);
            RepayRecord::where('id',$recordInfo->id)->update(['status' => RepayRecord::STATUS_TWO]);
            RepayRecordMoney::where('id',$recordInfo->money->id)->update(['status' => RepayRecordMoney::STATUS_TWO]);
            Log::debug('还款:月保费接口判断上个接口不是成功状态');
            return;
        }

        //判断是否处于可扣款状态
        if($recordInfo->month->status == RepayRecordMonth::STATUS_TWO){
            Log::debug('还款:请求月保费接口:在队列中不是要处理的状态' . $this->id);
            return;
        }elseif($recordInfo->month->status == RepayRecordMonth::STATUS_FOUR){
            //更新催收方数据
            event(new RepayMentEvent($recordInfo->summary_id));
            RepayCommonJobQueue::dispatch($recordInfo->id);
            Log::debug('还款:请求月保费接口:在队列中不是要处理的状态' . $this->id);
            return;
        }
        //对月保费进行还款
        $month_amount = $recordInfo->month->amount;
        $summaryInfo = RepaySummary::select('loan_id')->find($recordInfo->summary_id);
        $loan_id = $summaryInfo->loan_id;
        $trade_no = empty($recordInfo->month->trade_no) ? RepaySummary::createTradeNo($recordInfo->uid,'month') : $recordInfo->month->trade_no;
        if($month_amount == 0){
            $this->setMonthStatus($recordInfo->month);
            return;
        }else{
            //请求三方的接口
            $res = RepaySummary::setMonth($recordInfo->month->id,$month_amount,$loan_id,$trade_no,$recordInfo->period,$recordInfo->summary_id);
            if(!$res){
                Log::debug('还款:请求月保费接口:不正确' . $this->id);
                return;
            }
        }
        //改变状态
        //改变状态 用户全局状态为轮询中,记录总表为轮询中,两个分表为轮询中 开启事务
        DB::beginTransaction();
        try{
            //改变状态
            UserGlobal::where('uid',$recordInfo->uid)->update(['global_status' => UserGlobal::STATUS_REPAY_ING]);
            RepayRecord::where('id',$recordInfo->id)->update(['status' => RepayRecord::STATUS_TWO]);
            RepayRecordMonth::where('id',$recordInfo->month->id)->update(['status'=>RepayRecordMonth::STATUS_TWO,'trade_no' => $trade_no]);
            RepaySummary::checkApiNumber($recordInfo->summary_id,$recordInfo->uid,RepaySummary::MONEY_API,2);
            DB::commit();
        }catch(\Exception $exception){
            Log::debug("还款:请求月保费接口队列:更新UserGlobal,RepayRecord,RepayRecordMonth失败".$exception->getMessage());
            DB::rollBack();
            return;
        }
    }

    //月保费为0的时候更改状态
    protected function setMonthStatus(RepayRecordMonth $model){
        try {
            DB::beginTransaction();
            if (0 == $model->period) {
                //全部还清
                //本队列对应的公共表
                foreach ($model::where([
                    ['summary_id', '=', $model->summary_id],
                    ['status', '<>', $model::STATUS_FOUR],
                ])->cursor() as $record_month_model) {
                    $record_month_model->amount = 0; //提前结清的月保费0
                    $record_month_model->status = $model::STATUS_FOUR;
                    $record_month_model->status_time = Carbon::now();
                    $record_month_model->save();
                }
            } else {
                //单期还清
                //本队列对应的公共表
                $model->update([
                    'status' => $model::STATUS_FOUR,
                    'status_time' => Carbon::now(),
                ]);
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
        }
        Log::debug('还款:month月报费为0');
        //调用公共接口队列
        RepayCommonJobQueue::dispatch($model->record_id);
        return 0;
    }

}
